package com.dandelion.framework.common;

import com.dandelion.framework.enums.CodeEnum;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;


/**
 * 统一返回参数
 *
 * @author 77088
 * @date 2022/02/16
 */
@ToString
@EqualsAndHashCode
@Getter
@ApiModel(value = "R响应结果")
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class R<T> implements Serializable {

    @ApiModelProperty(value = "响应编码:0-请求处理成功")
    private int code;

    @ApiModelProperty(value = "提示消息")
    private String msg;

    @ApiModelProperty(value = "响应数据")
    private T data;

    @ApiModelProperty(value = "附加数据")
    private Map<String, Object> extra;


    public static R ok() {
        R r = new R();
        r.setCode(0);
        r.setMsg("ok");
        return r;
    }

    public static R fail() {
        R r = new R();
        r.setCode(1000);
        r.setMsg("error");
        return r;
    }

    public static R fail(int code, String msg) {
        R r = new R();
        r.setCode(code);
        r.setMsg(msg);
        return r;
    }

    public static R fail(CodeEnum codeEnum) {
        R r = new R();
        r.setCode(codeEnum.getCode());
        r.setMsg(codeEnum.getMsg());
        return r;
    }

    public R code(int code) {
        this.setCode(code);
        return this;
    }

    public R msg(String msg) {
        this.setMsg(msg);
        return this;
    }

    public R data(T data) {
        this.setData(data);
        return this;
    }

    public R codeMsg(int code, String msg) {
        this.setCode(code);
        this.setMsg(msg);
        return this;
    }

    public R put(String key, String val) {
        Map<String, Object> extra = this.getExtra();
        if (extra == null) {
            extra = new HashMap<>();
            this.setExtra(extra);
        }
        extra.put(key, val);
        return this;
    }
}